<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/1/30
 * Time: 下午2:37
 */

namespace app\common\Utils;

use app\common\ShaoHuoPay\Exceptions\Exception;
use app\common\ShaoHuoPay\Pay;
use app\api\controller\Errorcode;

class AliPay
{
    public $config;

    public function __construct()
    {
        $this->config = [
            'app_id'            => config('pay')['ALI_PAY_V2']['APPID'],
            'notify_url'        => config('pay')['ALI_PAY_V2']['notify_url'],
            'ali_public_key'    => config('pay')['ALI_PAY_V2']['ali_public_key'],
            'private_key'       => config('pay')['ALI_PAY_V2']['ali_private_key'],
        ];
    }

    public function doPay($order_info)
    {
        if(PayMent::PAY_ALIPAY_APP != $order_info['shareId']){
            return [
                'msg' => Errorcode::$code['400001'] . $order_info['shareId'],
            ];
        }

        $order = [
            'out_trade_no' => trim($order_info['order_num']),//生成订单号 保存在系统内部使用
            'total_amount' => config('app_debug') == true ?'0.01':$order_info['total_fee'],
            'subject' => $order_info['body'],
        ];
        $str = Pay::alipay($this->config)->app($order)->getContent();
        return $str;
    }

    /**
     * 退款订单
     * @param $refound_order
     * @return mixed
     */
    public function refound($refound_order)
    {

        $order = [
            'out_trade_no' => $refound_order['out_trade_no'],
            'refund_amount' => $refound_order['total_amount']/100,
        ];

        try {
            $res = Pay::alipay($this->config)->refund($order);

            if($res->code == '10000' && $res->msg == 'Success'){
                return ['code'=>'success','msg'=>'退款成功'];
            }
        } catch (Exception $exception){
            return ['code'=>'fail','msg'=> $exception->getMessage()];
        }


    }
}